//
//  SIStatusPictureView.swift
//  SinaImiate
//
//  Created by xiaoming on 16/7/6.
//  Copyright © 2016年 GoodJob. All rights reserved.
//

import UIKit

class SIStatusPictureView: UIView {
    
    ///接收模型,在类内部设置计算视图属性
    var viewModel: SIStatusViewModel? {
        
        didSet {
            
            calcViewSize()
            
            urls = viewModel?.picURLs
            
        }
    }
    
    ///根据视图模型的配图视图大小, 调整显示内容
    private func calcViewSize() {
        
        if viewModel?.picURLs?.count == 1 {
            
            let viewSize = viewModel?.pictureViewSize ?? CGSize()
            
            let v = subviews[0]
            
            v.frame = CGRect(x: 0, y: SIStatusPictureViewOutterMargin, width: viewSize.width, height: viewSize.height - SIStatusPictureViewOutterMargin)
            
        } else {
            
            let v = subviews[0]
            
            v.frame = CGRect(x: 0, y: SIStatusPictureViewOutterMargin, width: SIStatusPictureItemWidth, height: SIStatusPictureItemWidth)
            
        }
        
        ///修改高度约束
        heightCons.constant = viewModel?.pictureViewSize.height ?? 0
        
    }
    
    ///图像数组
    private var urls: [SIStatusPicture]? {
        didSet {
            for v in subviews {
                
                v.isHidden = true
            }
            
            var index = 0
            
            for url in urls ?? [] {
                
                let iv = subviews[index] as! UIImageView
                
                if index == 1 && urls?.count == 4 {
                    
                    index += 1
                }
                
                iv.cz_setImage(urlString: url.thumbnail_pic, placeholderImage: nil)
                
                iv.subviews[0].isHidden = (((url.thumbnail_pic ?? "") as NSString).pathExtension.lowercased() != "gif")
                
                iv.isHidden = false
                
                index += 1
            }
        }
    }

    @IBOutlet weak var heightCons: NSLayoutConstraint!
    
    override func awakeFromNib() {
        
        setupUI()
    }
    
    @objc private func tapImageView(tap: UITapGestureRecognizer) {
        
//        let iv = tap.view
        guard let iv = tap.view,
            let picURLs = viewModel?.picURLs
            else {
                return
        }
        
        var selectedIndex = iv.tag
        
        if picURLs.count == 4 && selectedIndex > 1 {
            selectedIndex -= 1
        }
        
        let urls = (picURLs as NSArray).value(forKey: "largePic") as! [String]
        
        var imageViewList = [UIImageView]()
        
        for iv in subviews as! [UIImageView] {
            
            if !iv.isHidden {
                imageViewList.append(iv)
            }
            
        }
        
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: SIStatusCellBrowserPhotoNotification), object: self, userInfo: [
            SIStatusCellBrowserPhotoSelectedIndexKey: selectedIndex,
            SIStatusCellBrowserPhotoImageViewsKey: imageViewList,
            SIStatusCellBrowserPhotoURLsKey: urls
            ])
    }

}

extension SIStatusPictureView {
    
    
    ///cell中所有的控件都要提前准备好,设置的时候,根据数量决定是否显示, 不要动态创建控件
    private func setupUI() {
        
        backgroundColor = superview?.backgroundColor
        
        clipsToBounds = true
        
        let count = 3
        
        let rect = CGRect(x: 0, y: SIStatusPictureViewOutterMargin, width: SIStatusPictureItemWidth, height: SIStatusPictureItemWidth)
        
        for i in 0..<count * count {
            
            let iv = UIImageView()
            
            iv.contentMode = .scaleAspectFill
            iv.clipsToBounds = true
            
            iv.backgroundColor = UIColor.red()
            
            let row = CGFloat(i / count)
            
            let col = CGFloat(i % count)
            
            let xOffset = col * (SIStatusPictureItemWidth + SIStatusPictureViewInnerMargin)
            
            let yOffset = row * (SIStatusPictureViewInnerMargin + SIStatusPictureItemWidth)
            
            iv.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            
            addSubview(iv)
            
            iv.isUserInteractionEnabled = true
            
            let tap = UITapGestureRecognizer(target: self, action: #selector(tapImageView))
            
            iv.addGestureRecognizer(tap)
            
            iv.tag = i
            
            addGifView(iv: iv)
        }
        
    }
    
    private func addGifView(iv: UIImageView) {
        let gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
        
        iv.addSubview(gifImageView)
        
        gifImageView.translatesAutoresizingMaskIntoConstraints = false
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .right, relatedBy: .equal, toItem: iv, attribute: .right, multiplier: 1.0, constant: 0))
        
        iv.addConstraint(NSLayoutConstraint(item: gifImageView, attribute: .bottom, relatedBy: .equal, toItem: iv, attribute: .bottom, multiplier: 1.0, constant: 0))
        
    }
    
}
